import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService} from 'primeng/api';
import {BasePage} from '../../base.page';
import {PUblicMethod} from '../../services/PUblicMethod';
import {VariationService} from '../variation.service';
import {VariationObjModel} from '../variationObj.model';
import {SimpleFormContentComponent} from '../public/simple-form-content/simple-form-content.component';
import {UnvariationTableComponent} from '../public/unvariation-table/unvariation-table.component';
import {SelectEquipmentsComponent} from '../../public/select-equipments/select-equipments.component';
import {EventBusService} from '../../services/event-bus.service';

@Component({
  selector: 'app-approve-variation',
  templateUrl: './approve-variation.component.html',
  styleUrls: ['./approve-variation.component.scss']
})
export class ApproveVariationComponent extends  BasePage implements OnInit {

    @ViewChild('simpleFormContent') simpleFormContent: SimpleFormContentComponent;
    @ViewChild('unvariationTable') unvariationTable: UnvariationTableComponent;
    @ViewChild('selectEquipments') selectEquipments: SelectEquipmentsComponent;
    formTitle = '审批申请单';
    myForm: FormGroup;
    formObj: VariationObjModel;
    displayPersonel: boolean = false;              // 人员组织组件是否显示
    controlDiaglog: boolean;

    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private variationService: VariationService,
                public messageService: MessageService,
                private eventBusService: EventBusService,
                public confirmationService: ConfirmationService) {
        super(confirmationService, messageService);
    }

    ngOnInit() {
        this.formObj = new VariationObjModel();
        this.initMyForm();
        this.getQueryParams();
        this.controlDiaglog = false;
    }

    initMyForm = () =>  {
        this.myForm = this.fb.group({
            approve_remarks: [null, Validators.required],
            executor_org: [null, Validators.required]
        });
    };

    goBack = () => {
        this.eventBusService.variationFlowCharts.next('');
        this.router.navigate(['../overview'], {relativeTo: this.activedRouter});
    };

    isFieldValid = name => {
        return PUblicMethod.isFieldValid(this.myForm, name);
    };

    operate = result => {
        this.formObj.status = result;
        if (!this.formObj.executor || !this.formObj.executor_org) {
            PUblicMethod.validateAllFormFields(this.myForm);
        } else {
            this.requestApprove();
        }
    };

    requestApprove = () =>  {
        this.variationService.requestApprove(this.formObj).subscribe(res => {
            if (res === '00000') {
                this.alert('操作成功');
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            } else {
                this.alert(`操作失败${res}`, 'error');
            }
        });
    }

    unaccessTableDatasEimitter = device => {
        // this.unaccessEquipTabel.tableDatas = device;
    }

    getQueryParams = () => {
        this.activedRouter.queryParams.subscribe(params => {
            (params['sid']) && (this.formObj.sid = params['sid']);
            this.requestMesageBySid(params['sid']);
            (params['status']) && (this.eventBusService.variationFlowCharts.next(params['status']));
        });
    };

    requestMesageBySid = id => {
        this.variationService.getMesageBySid(id).subscribe(res => {
            if (res['errcode'] === '00000') {
                this.formObj = new VariationObjModel(res['data']);
                this.simpleFormContent.formObj = new VariationObjModel(res['data']);
                this.unvariationTable.tableDatas = res['data']['devices'];
                this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(res['data']['devices']);
            }else {
                this.alert(`获取出入单信息失败 + ${res['errmsg']}`, 'error');
            }
        });
    };

    showPersonDialog = () => {this.displayPersonel = true; };

    clearPersonDialog = () => {
        this.formObj.executor = '';
        this.formObj.executor_pid = '';
        this.formObj.executor_org = '';
        this.formObj.executor_org_oid = '';
    };

    dataEmitter = event => {
        this.formObj.executor = event.name;
        this.formObj.executor_pid = event.pid;
        this.formObj.executor_org = event.organization;
        this.formObj.executor_org_oid = event.oid;
    };

    displayEmitter = event => { this.displayPersonel = event; };

    selectedEquipsEmitter = event => {
        event.forEach(arrayItem => {
            this.unvariationTable.tableDatas.push(arrayItem);
        });
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.unvariationTable.tableDatas);
    };

    getSelectedAnoArray = (data): any => {
        let anoArray = [];
        for (let i = 0; i < data.length; i++ ) {
            anoArray.push(data[i]['ano']);
        }
        return anoArray;
    };

    dcontrolDialogHandler = (event) => {
        this.controlDiaglog = event;
    };

    openEquipList = () =>  {
        this.controlDiaglog = true;
    };

    removeEquipmenst = () => {
        for (let i = 0; i < this.unvariationTable.selectedCars3.length; i++) {
            this.unvariationTable.tableDatas = this.unvariationTable.tableDatas.filter(v => {
                return !(v['ano'] === this.unvariationTable.selectedCars3[i]['ano']);
            })
        }
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.unvariationTable.tableDatas);
    };
}
